<template>
    <vxe-modal v-model="systemRoleManagerStore.isShowAddSystemMenuModel"
               :loading="isFormLoading"
               esc-closable
               show-footer
               title="新增系统角色">
        <vxe-form
            ref="formRef"
            border
            title-background
            title-align="right"
            title-width="120"
            title-overflow
            :data="systemMenuAddFormData"
            :rules="formRules"
            :valid-config="{theme: 'normal'}">

            <vxe-form-item title="角色名称"
                           field="roleName"
                           span="24"
                           :item-render="{}"
                           :title-prefix="{ content: '角色名称', icon: 'vxe-icon-num-list' }">
                <template #default>
                    <vxe-input v-model="systemMenuAddFormData.roleName" placeholder="请输入角色名称"/>
                </template>
            </vxe-form-item>
        </vxe-form>

        <template #footer>
            <vxe-button style="margin-left: 10px;" icon="vxe-icon-undo" @click="cancelEdit">取消</vxe-button>
            <vxe-button status="primary" icon="vxe-icon-save" @click="submitForm">保存</vxe-button>
        </template>
    </vxe-modal>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {SystemRoleAddFormData} from "@/entiy/form/SystemRoleAddFormData.ts";
import {useSystemRoleManagerStore} from "@/store/UseSystemRoleManagerStore.ts";
import XEUtils from "xe-utils";
import {VxeFormInstance, VxeFormPropTypes} from "vxe-pc-ui";
import {DialogUtils} from "@/utils/DialogUtils.ts";

const systemRoleManagerStore = useSystemRoleManagerStore();

// 表单的引用
const formRef = ref<VxeFormInstance<SystemRoleAddFormData>>();

// 表单是否正在加载中
const isFormLoading = ref(false)

// 表单数据
const systemMenuAddFormData = ref<SystemRoleAddFormData>({
    roleName: ''
});

// 表单校验规则
const formRules = {
    roleName: [
        {
            required: true,
            content: '角色名称不能为空'
        },
        {
            validator({itemValue}) {
                if (XEUtils.getSize(itemValue) > 8) {
                    return new Error('长度超出范围[1-8]')
                }
            }
        }
    ],
} as VxeFormPropTypes.Rules;

// 表单取消按钮
const cancelEdit = () => {
    isFormLoading.value = false;
    systemRoleManagerStore.isShowAddSystemMenuModel = false;
};

// 表单提交按钮
const submitForm = () => {
    isFormLoading.value = true;
    systemRoleManagerStore.addSystemRole(systemMenuAddFormData.value).then(() => {
        // 关闭弹窗
        systemRoleManagerStore.isShowAddSystemMenuModel = false;
    }).catch((reason) => {
        DialogUtils.showUniqueDialog(reason);
    }).finally(() => {
        isFormLoading.value = false;
    });
}
</script>